package com.gt.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gt.constant.MessageConstant;
import com.gt.constant.StatusConstant;
import com.gt.context.BaseContext;
import com.gt.exception.AmountException;
import com.gt.exception.BorrowFailedException;
import com.gt.exception.DeletionNotAllowedException;
import com.gt.exception.UserAreadyBorrowException;
import com.gt.mapper.BookMapper;
import com.gt.mapper.BorrowMapper;
import com.gt.pojo.PageResult;
import com.gt.pojo.dto.BookDTO;
import com.gt.pojo.dto.BookPageQueryDTO;
import com.gt.pojo.entity.Book;
import com.gt.pojo.entity.Borrow;
import com.gt.pojo.vo.BookVO;
import com.gt.service.BookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BorrowMapper borrowMapper;
    @Override
    public void save(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO,book);
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.insert(book);
    }

    @Override
    public PageResult pageQuery(BookPageQueryDTO bookPageQueryDTO) {
        PageHelper.startPage(bookPageQueryDTO.getPage(), bookPageQueryDTO.getPageSize());
        Page<BookVO> page = bookMapper.pageQuery(bookPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        bookMapper.deleteByIds(ids);
    }

    @Override
    public BookVO getById(Long id) {
        Book book = bookMapper.getById(id);
        BookVO bookVO = new BookVO();
        BeanUtils.copyProperties(book,bookVO);

        return bookVO;
    }

    @Override
    public void update(BookDTO bookDTO) {
        Book book =new Book();
        BeanUtils.copyProperties(bookDTO,book);
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.update(book);
    }

    @Override
    public List<Book> list(Long categoryId) {
        Book book = Book.builder()
                .categoryId(categoryId)
                .build();
        return bookMapper.list(book);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByNumber(Long id) {
        Book book = bookMapper.getById(id);
        if (book.getNumber() == 0){
            throw new AmountException("图书数量不足");
        }
        Long userId = BaseContext.getCurrentId();
        List<Borrow> borrow1 = borrowMapper.selectByBookId(id, userId);
        for (Borrow borrow : borrow1) {
            Integer status = borrow.getStatus();
            if (status == 6){
                throw new BorrowFailedException("借书异常，请联系管理员");
            }
        }
        if (borrow1 != null || borrow1.size()>0){
            for (Borrow borrow : borrow1) {
                if (borrow.getStatus() != StatusConstant.RETURNED){
                    throw new UserAreadyBorrowException(MessageConstant.USE_RLREADY_BORROW_BOOK);
                }
            }
        }
        Borrow borrow = Borrow.builder()
                .bookId(book.getId())
                .userId(BaseContext.getCurrentId())
                .status(StatusConstant.BORROWING)
                .name(book.getName())
                .startTime(LocalDateTime.now())
                .endTime(LocalDateTime.now().plusDays(15))
                .build();

        borrowMapper.insert(borrow);
        book.setNumber(book.getNumber()-1);
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.update(book);
    }

    @Override
    public void deleteById(Long id) {
        // 根据借阅ID查询借阅记录
        List<Borrow> borrow =borrowMapper.selectByBoId(id);
        // 如果存在借阅记录，则进一步检查
        if(borrow != null && borrow.size()>0){
            // 遍历借阅记录，检查是否有未归还的书籍
            for (Borrow borrow1 : borrow) {
                // 如果借阅记录中的书籍未归还且与给定的书籍ID匹配，则抛出异常，不允许删除
                if (borrow1.getStatus() != StatusConstant.RETURNED && borrow1.getBookId().equals(id)) {
                    throw new DeletionNotAllowedException(MessageConstant.BOOK_BE_RELATED_BY_BORROW);
                }
            }
        }


        bookMapper.deleteById(id);
    }
}
